package com.demo.gateway.service.impl;

import static com.demo.gateway.routes.GatewayConstant.GATEWAY_REDIS_ROUTES;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.gateway.pojo.GatewayRouteDO;
import com.demo.gateway.util.JsonUtil;

/**
 * @author: demo
 * @date: 2020年6月18日
 * @Document : redis 存储 增,删 ,查
 */
@Service
public class RedisRouteService {
	private String redisRoute = GATEWAY_REDIS_ROUTES.name();
	private BoundHashOperations<String, String, String> redisHashOps;

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@PostConstruct
	private void init() {
		redisHashOps = redisTemplate.boundHashOps(this.redisRoute);
	}

	public void addRedisRoute(String key, String value) {
		redisHashOps.put(key, value);
	}

	public void deleteRedisRoute(Object... keys) {
		redisHashOps.delete(keys);
	}

	public JSONArray queryRedisRoute() {
		JSONArray redisResults = new JSONArray();
		JSONObject data = null;
		for (String key : redisHashOps.keys()) {
			data = new JSONObject();
			data.put("routeId", key);
			data.put("routeInfo", redisHashOps.get(key));
			redisResults.add(data);
		}
		return redisResults;
	}
	/**
	 * 获取路由
	 * @return
	 */
	public List<GatewayRouteDO> queryRedisRoutes(){
		List<GatewayRouteDO> routeBeans=new ArrayList<GatewayRouteDO>(100);
		GatewayRouteDO routeBean=null;
		for (String key : redisHashOps.keys()) {
			routeBean=JSONObject.parseObject(redisHashOps.get(key),GatewayRouteDO.class);
		    routeBeans.add(routeBean);
		}
		return routeBeans;
	}
	
	/**
	 * 批量添加路由
	 * @param routeBeans
	 */
	public  void   addRedisRoutes(List<GatewayRouteDO> routeBeans) {
		routeBeans.forEach(routeBean->{
			 addRedisRoute(routeBean.getId(), JsonUtil.toString(routeBean));
		});
	}
	
}
